package top.jamsee.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/*
* this is file util
* @return  map (0:if success,1:filename)
* */
public  class  fileUpload {
    public static String uploadFile(HttpServletRequest request) {
        //实例化磁盘被文件列表工厂
        DiskFileItemFactory sf= new DiskFileItemFactory();
        //得到上传文件的存放目录
        //我要跳出编译路径,以防全部文件夹被重新编译只能这样做
        String path = request.getServletContext().getRealPath("/")+"/upload";
        System.out.println(path);
        //设置文件存放目录
        sf.setRepository(new File(path));
        //设置文件上传小于1M放在内存中
        sf.setSizeThreshold(1024*1024);
        //文件新生成的文件名
        String rename = "";
        //文件原名称
        String fileName = "";
        //普通field字段
        String name = "";
        //从工厂得到servletupload文件上传类
        ServletFileUpload sfu = new ServletFileUpload(sf);
        //如果文件夹不存在创建文件夹
        File file=new File(path);
        if (!file.isDirectory()){
            file.mkdir();

        }
        System.out.println("生成一个文件夹");

        try {
            //得到request中所有的元素
            List<FileItem> lst = sfu.parseRequest(request);
            for (FileItem fileItem : lst) {
                if(fileItem.isFormField()){
                    if("name".equals(fileItem.getFieldName())){
                        name = fileItem.getString("UTF-8");
                    }
                }else{
                    //获得文件名称
                    fileName = fileItem.getName();
                    System.out.println(fileName);
                    fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
                    String houzhui = fileName.substring(fileName.lastIndexOf("."));
                    System.out.println("houzhui"+houzhui);
                    rename = UUID.randomUUID()+houzhui;
                    fileItem.write(new File(path, rename));
                }

            }
            System.out.println(rename);
        } catch (Exception e) {
            //如果失败返回空字符串
            return "none";

        }

        return rename;



    }


}
